package com.lqian.time.localdate;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 解决方案2：加锁：synchronized锁和Lock锁
 * ====>    加Lock锁也能保证线程安全。
 *          要注意的是，最后一定要释放锁，代码里在finally里增加了lock.unlock();，保证释放锁。
 *          在高并发的情况下会影响性能。这种方案不建议在高并发场景下使用
 */
public class SimpleDateFormatTest3 {
    // private static  类共享的
    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static Lock lock = new ReentrantLock();
    public static void main(String[] args) throws ParseException {
        //1.创建线程池
        ExecutorService pool = Executors.newFixedThreadPool(10);
        //2.为线程池分配任务
        ThreadPoolTest task = new ThreadPoolTest();
        for (int i = 0; i <10 ; i++) {
            pool.submit(task);
        }
        //3.关闭线程
        pool.shutdown();
        }

    static class ThreadPoolTest implements Runnable{

        @Override
        public void run() {

            try {
                    lock.lock();
                    String dateString1 = simpleDateFormat.format(new Date());
                    Date date = simpleDateFormat.parse(dateString1);
                    String dateString2 = simpleDateFormat.format(date);
                    System.out.println(Thread.currentThread().getName() + " 线程是否安全: " + dateString1.equals(dateString2));
            } catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }

        }
    }


}
